//
//  LGMainViewController.swift
//  微博框架
//
//  Created by ming on 16/10/3.
//  Copyright © 2016年 ming. All rights reserved.
//

import UIKit
import SVProgressHUD

class LGMainViewController: UITabBarController {
    var timer:Timer?
    var results:(()->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置界面
        setUI()
        //有token才开启定时器
        LGNetWorKingManager.shared.accessToken() ? loadTime():()
        self.delegate = self
        notification()
      
    }
    //移除通知,移除定时器
    deinit {
        NotificationCenter.default.removeObserver(self)
        timer?.invalidate()
    }

}

// MARK: - 通知事件
extension LGMainViewController{
    
    func notification(){
        NotificationCenter.default.addObserver(self, selector: #selector(login), name: NSNotification.Name(rawValue: Notificationuserlogin), object: nil)
       
    }
    
       
    
@objc private func login(){
        
        print("通知登录")
   let vc =  LGAuthController()
    let nv = UINavigationController(rootViewController: vc)
    self.present(nv, animated: true, completion: nil)
        
    }
    
    
}




// MARK: - 设置界面
extension LGMainViewController{
    
   func setUI(){
  
        setChildViewControllersDitc()
        setWritButton()
    
    
    }
    //添加撰写按钮
    func setWritButton(){
        
       let writButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
        //让其-1让按钮往外拉伸覆盖误差点
        let butnW = UIScreen.cz_screenWidth() / CGFloat((viewControllers?.count)!) - 1
        
        writButton?.frame = tabBar.bounds.insetBy(dx: 2 * butnW, dy: 0)
        tabBar.addSubview(writButton!)
        
        
    }
    
    ///传一个字典数据过去根据反射机制动态添加控制器
    private func setChildViewControllersDitc(){
        //创建一个字典数组
       
      
        
        
       
        guard  let path = Bundle.main.path(forResource: "dict.json", ofType: nil),
         let data = NSData(contentsOfFile: path) as? Data,
         let dictArray  = try? JSONSerialization.jsonObject(with:data , options: []) as! [[String:Any]]
        else {
            return
        }
        
        //创建一个可变的数组
        var arrayM = [UIViewController]()
        //遍历出字典
        for dict in dictArray {
            //得到一个控制器我们需要用数组把它保存起来
            arrayM.append(setChildViewControllers(dict: dict))
        }
        
        viewControllers = arrayM
        
    }
    
    //反射机制通过字典添加控制爱
  private  func setChildViewControllers(dict:[String:Any]) -> UIViewController {
        
        
        /// 如果有空那么就返回一个默认控制器
        guard  let calssName = dict["className"] as? String,
        let imageName = dict["image"] as? String,
        let vcTitle = dict["title"] as? String else {
            return UIViewController()
        }
        
        //swift里面控制器的类名是根据命名空间的名称+"."+"控制名"
        let clName = Bundle.main.namespace + "." + calssName as String
       //字符串转换
      let vc = (NSClassFromString(clName) as! LGBasiViewController.Type).init()
        //设置控制器属性
        vc.title = vcTitle
    //设置访客字典
    vc.vistorDictInfo = dict["visitor"] as! [String : String]?
    
       vc.tabBarItem.image = UIImage(named:"tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)        //创建导航控制器
    vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
//    vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
    
        let nv = LGNavigationController(rootViewController:vc)
        
        return nv
        
    }
    
    
}

extension LGMainViewController{
    
    func loadTime(){
        
        timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(time), userInfo: nil, repeats: true)
       
    }
@objc private func time(){
        
        uncount()
        
    }
    
    func uncount(){
        LGNetWorKingManager.shared.unreadCount { (count) in

            print("有\(count)未读")
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
        }
       
    }
    
    
    
}

extension LGMainViewController:UITabBarControllerDelegate{
    
    
    //点击tabbar按钮会调用这个方法
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        //获取当前点击的控制器
     
        //拿到根控制器
       
        //获取当前控制器对应的索引
        let array = childViewControllers as NSArray
        let index = array.index(of: viewController)
   
        if index == selectedIndex && index == 0{

            let nav = childViewControllers[0] as! LGNavigationController
            let vc = nav.childViewControllers[0] as! LGHomeViewController
            //FXMI:问题1
            vc.tableView?.setContentOffset(CGPoint(x: 0 ,y: 0), animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { 
                vc.loadData()
               
            })
            

            
        }
        
        
        
        
        return true
    }
    
}




